import { ref, computed,watch } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
    // 定义当前查找的城市
    const selectCity = ref('')
    // 定义当前查找的城市的adcode
    const selectCityAdcode = ref('')
    // 定义总共保存的城市和气温
    const showCitys = ref([])
    // 定义当前查找城市的天气
    const cityWeather = ref([])

    // 定义是否显示+号
    const isShowjia = ref(true)

    // 将当前城市以及adcode赋值
    const changeDatas = (value,adcode)=>{
      selectCity.value =value
      selectCityAdcode.value = adcode
    }

    // 当前城市天气赋值
    const weatherDatas = (value)=>{
      cityWeather.value = value
    }

    // 保存当前的城市和气温进入数组
    const addDatas = ()=>{
      let mess = [ selectCity.value,cityWeather.value[0].daytemp,selectCityAdcode.value ]
      showCitys.value.push(mess)
    }
    // 删除其中保存的某个数据
    const deleteDatas = (index)=>{
      showCitys.value.splice(index,1)
    }

    // 监听数据变化,保存本地
    watch(
      showCitys,
      ()=>{
        localStorage.setItem('showCitys',JSON.stringify(showCitys.value))
      },
      {
        deep:true,
      }
    )
    // 从本地加载数据
    const getShowCitys = ()=>{
      showCitys.value = JSON.parse(localStorage.getItem('showCitys') || '[]' )
    }

  return { 
    selectCity,
    selectCityAdcode,
    showCitys,
    cityWeather,
    isShowjia,
    changeDatas,
    weatherDatas,
    addDatas,
    deleteDatas,
    getShowCitys,
   }
})
